﻿
using Xacml.Core;
using Xacml.Core.Context;
using Xacml.Core.Interfaces;
using Xacml.Core.Policy;
using Xacml.Core.Runtime;
using System.Collections;
using System.Security.Permissions;
using System.Xml;

namespace Xacml.Core.Extensions
{
  public class DefaultAttributeRepository : IAttributeRepository
  {
    private AttributeCollection _attributes = new AttributeCollection();

    [PermissionSet(SecurityAction.Demand, XML = "<PermissionSet class=\"System.Security.PermissionSet\"\r\n               version=\"1\">\r\n   <IPermission class=\"System.Security.Permissions.ReflectionPermission, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\"\r\n                version=\"1\"\r\n                Flags=\"TypeInformation\"/>\r\n</PermissionSet>\r\n")]
    public void Init(XmlNode configNode)
    {
      foreach (XmlNode xmlNode1 in configNode.ChildNodes)
      {
        if (xmlNode1.Name == "Attribute")
        {
          XmlNode xmlNode2 = xmlNode1.SelectSingleNode("./AttributeValue");
          string attributeId = xmlNode1.Attributes["AttributeId"].Value;
          string issuer = xmlNode2.Attributes["Issuer"] != null ? xmlNode2.Attributes["Issuer"].Value : "";
          string dataType = xmlNode2.Attributes["DataType"] != null ? xmlNode2.Attributes["DataType"].Value : "";
          this._attributes.Add((AttributeElementReadWrite) new AttributeElement(attributeId, dataType, issuer, (string) null, xmlNode2.InnerText, XacmlVersion.Version11));
        }
      }
    }

    public AttributeElement GetAttribute(EvaluationContext context, AttributeDesignatorBase designator)
    {
      foreach (AttributeElement attributeElement in (CollectionBase) this._attributes)
      {
        if (attributeElement.AttributeId == designator.AttributeId && (designator.Issuer == null || designator.Issuer.Length == 0 || designator.Issuer == attributeElement.Issuer))
          return attributeElement;
      }
      return (AttributeElement) null;
    }
  }
}
